package com.atguigu.sprincloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.sprincloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName:
 * @Description:
 * @version: v1.1.0
 * @author: shuaiqin
 * @date: 2021/8/31-17:02
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2021/8/31          shuaiqin          v1.1.0               修改原因
 */
@Service
public class PaymentServiceImpl implements PaymentService {
    @Override
    public String paymentOk(Integer id) {
        return "线程池： "+Thread.currentThread().getName()+"  paymentOk"+id+"\t"+"成功！";
    }

    @Override
    @HystrixCommand(fallbackMethod = "payment_TimeHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
    })
    public String paymentTimeEror(Integer id) {
        int timeNumber = 2;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池： "+Thread.currentThread().getName()+"  paymentTimeEror"+id+"\t"+"耗时"+timeNumber;
    }

    public String payment_TimeHandler(Integer id){
        return "线程池： "+Thread.currentThread().getName()+"  payment_TimeHandler"+id+"\t"+"服务端繁忙 稍后再试";
    }
    //下面是全局fallback
    public String payment_Global_FallbackMethod(){
        return "Global异常处理信息，请稍后再试!";
    }

    @Override
    @HystrixCommand(fallbackMethod = "payment_CircuitBreakerFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数峰值达到10次
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期 熔断到尝试恢复的时间
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//失败率达到多少跳闸
    })
    public String paymentTimeCircuitBreaker(Integer id) {
        if(id<0){
            throw new RuntimeException("***id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return "线程池： "+Thread.currentThread().getName()+"流水号 "+serialNumber;
    }

    public String payment_CircuitBreakerFallback(Integer id){
        return "id 不能为负数，请稍后再试！"+id;
    }
}
